import Vue from 'vue'
import Vuex from 'vuex'

function loadJSON(JSONContent) {
  try {
    return JSON.parse(JSONContent)
  } catch (e) {
    return null
  }
}

const state = {
  user: loadJSON(localStorage.getItem('user')) || loadJSON(sessionStorage.getItem('user')) || {},
  loading: false,
}

const actions = {
  /**
   * 用户登录注册
   * @param commit
   * @param user
   * @constructor
   */
  LOGIN({ commit }, user) {
    user.loginAt = new Date().toLocaleDateString()
    if (user.logout) {
      sessionStorage.removeItem('user')
      localStorage.removeItem('user')
    } else if (user.remember) {
      localStorage.setItem('user', JSON.stringify(user, null, 2))
    } else {
      sessionStorage.setItem('user', JSON.stringify(user, null, 2))
    }
    commit('LOGIN', user)
  },
  /**
   * API 是否在加载
   * @param commit
   * @param loading
   * @constructor
   */
  LOADING({ commit }, loading = true) {
    commit('LOADING', loading)
  },
}

const mutations = {
  LOGIN(state, user) {
    if (user.logout) {
      state.user = {}
    } else {
      state.user = user
    }
  },
  LOADING(state, loading) {
    state.loading = loading
  },
}

Vue.use(Vuex)
export default new Vuex.Store({
  state,
  mutations,
  actions,
})
